﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Game.Foundation.ChineseChess;
using Game.Foundation;
using MF.Networker;

namespace Game.Client
{
    public partial class ChessGameForm : Form, IChildClient
    {
        private GameStatus _status;
        private GameConnection _gameConnection;
        private ChessboardClient _board;
        private Label _selected;
        private string _myName;
        private string _currentUserName;
        private string _key;

        public int GroupID { get; private set; }

        public Camp MyCamp { get; set; }

        public ChessGameForm(GameConnection client, string username, string key, int groupId)
        {
            InitializeComponent();

            this._gameConnection = client;
            this.GroupID = groupId;
            this._myName = username;
            this._key = key;

            
            RemoteServer.GetSingletomServer(Program.Port).RegisterChild(this._key, this);
            //this._gameConnection.CurrentHandExchanged += new EventHandler<Game.Foundation.ExchangeHandEventArgs>(_client_CurrentHandExchanged);
            //this._gameConnection.ChessmanLocationMoved += new EventHandler<PacketEventArgs>(_client_ChessmanLocationMoved);
            //this._gameConnection.GameCompleted += new EventHandler<Game.Foundation.GameCompletedEventArgs>(_client_GameCompleted);
            //this._gameConnection.GameGroupChanged += new EventHandler<Game.Foundation.GameGroupChangedEventArgs>(_client_GameGroupChanged);


            this.Initialize();
        }

        void _client_GameGroupChanged(object sender, Game.Foundation.GameGroupChangedEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void _client_GameCompleted(object sender, Game.Foundation.GameCompletedEventArgs e)
        {
            //this.GameOver(e);
        }

        void _client_ChessmanLocationMoved(object sender, PacketEventArgs e)
        {
            //this.DoActionCrossThreads(() =>
            //{
            //    this.GameSynchronize(e.Packet as GamePacket);
            //});
        }

        void lable_Click(object sender, EventArgs e)
        {
            if (this._currentUserName != this._myName) return;


            Label selected = sender as Label;
            ChessmanBase chessman = selected.Tag as ChessmanBase;

            if (this._selected == null)
            {
                if (chessman.Camp == this.MyCamp)
                {
                    selected.BorderStyle = BorderStyle.FixedSingle;
                    this._selected = selected;
                }
            }
            else
            {
                if (chessman.Camp == this.MyCamp)
                {
                    this._selected.BorderStyle = BorderStyle.None;
                    selected.BorderStyle = BorderStyle.FixedSingle;
                    this._selected = selected;
                }
                else
                {
                    ChessmanBase myChessman = this._selected.Tag as ChessmanBase;
                    int xOld = myChessman.XLocation, yOld = myChessman.YLocation;
                    if (this._board.MoveChessman(myChessman, chessman.XLocation, chessman.YLocation))
                    {
                        this.DoOperation(xOld, yOld, chessman.XLocation, chessman.YLocation);

                        //this._gameConnection.MoveChessman(xOld, yOld, chessman.XLocation, chessman.YLocation);
                    }
                }
            }
        }

        void _client_CurrentHandExchanged(object sender, Game.Foundation.ExchangeHandEventArgs e)
        {
            //this.DoActionCrossThreads(() =>
            //{
            //    this._currentUserName = e.CurrentUserName;
            //    if (e.CurrentUserName == this._myName)
            //    {
            //        this.FlashWindow();
            //    }
            //});
        }

        private void btnReady_Click(object sender, EventArgs e)
        {
            RemoteServer.GetSingletomServer(Program.Port).RequestChangeStatus(this._key, GameStatus.Ready);
            //this._gameConnection.ChangeReadyStatus(Game.Foundation.GameStatus.Ready);
        }

        private void btnUnready_Click(object sender, EventArgs e)
        {
            RemoteServer.GetSingletomServer(Program.Port).RequestChangeStatus(this._key, GameStatus.Unready);
            //this._gameConnection.ChangeReadyStatus(Game.Foundation.GameStatus.Unready);
        }

        private void panelChessBoard_Paint(object sender, PaintEventArgs e)
        {
            using (Graphics g = e.Graphics)
            {
                Pen p = new Pen(Color.Black, 2);

                for (int i = 0; i < Chessboard.RowCount; i++)
                {
                    g.DrawLine(p, this._board.Points[i, 0], this._board.Points[i, Chessboard.ColumnCount - 1]);
                }
                for (int j = 0; j < 9; j++)
                {
                    g.DrawLine(p, this._board.Points[0, j], this._board.Points[Chessboard.RowCount - 1, j]);
                }
                g.DrawLine(p, this._board.Points[0, 3], this._board.Points[2, 5]);
                g.DrawLine(p, this._board.Points[0, 5], this._board.Points[2, 3]);
                g.DrawLine(p, this._board.Points[9, 3], this._board.Points[7, 5]);
                g.DrawLine(p, this._board.Points[9, 5], this._board.Points[7, 3]);
                g.FillRectangle(new SolidBrush(Color.Silver), new Rectangle(this._board.Points[4, 0], new Size(ChessboardClient.CellSize * 8, ChessboardClient.CellSize)));
                //g.DrawString("楚 河     汉 界", new Font("隶书", 35, FontStyle.Bold), new SolidBrush(Color.Red), this._board.Points[4, 0].X, this._board.Points[4, 0].Y);
            }
        }

        private void panelChessBoard_MouseClick(object sender, MouseEventArgs e)
        {
            if (this._selected == null) return;

            ChessmanBase chessman = this._selected.Tag as ChessmanBase;
            int xLocation = 0, yLocation = 0;
            if (this._board.GetAssociateLocation(e.Location, out xLocation, out yLocation))
            {
                int xOld = chessman.XLocation, yOld = chessman.YLocation;
                if (this._board.MoveChessman(chessman, xLocation, yLocation))
                {
                    this.DoOperation(xOld, yOld, chessman.XLocation, chessman.YLocation);
                    //this._gameConnection.MoveChessman(xOld, yOld, chessman.XLocation, chessman.YLocation);
                }
            }
        }

        private void DoOperation(int xOld, int yOld, int xNew, int yNew)
        {
            GamePacket p = new GamePacket(PacketType.游戏操作请求包);
            p.Body.AddRange(BitConverter.GetBytes(xOld));
            p.Body.AddRange(BitConverter.GetBytes(yOld));
            p.Body.AddRange(BitConverter.GetBytes(xNew));
            p.Body.AddRange(BitConverter.GetBytes(yNew));

            RemoteServer.GetSingletomServer(Program.Port).RequestDoOperation(this._key, p);
        }

        #region IChildClient 成员


        public void Initialize()
        {
            this._currentUserName = string.Empty;
            this._board = new ChessboardClient(this.panelChessBoard);

            foreach (Control lable in this.panelChessBoard.Controls)
            {
                if (lable is Label)
                {
                    lable.Click += new EventHandler(lable_Click);
                }
            }
        }

        public void ExchangeHand(int seatIndex)
        {
            throw new NotImplementedException();
        }

        public void GameSynchronize(GamePacket synchronizePacket)
        {
            BytesParser translater = new BytesParser(synchronizePacket.Body.ToArray());
            int xOld = translater.GetInt();
            int yOld = translater.GetInt();
            int xNew = translater.GetInt();
            int yNew = translater.GetInt();

            this._board.MoveChessman(xOld, yOld, xNew, yNew);
        }

        public void GameOver(GameCompletedEventArgs e)
        {
            string msg = string.Empty;
            foreach (var item in e.ResultList)
            {
                msg += string.Format("{0}得分：{1}{2}", item.UserName, item.Score, Environment.NewLine);
            }
            this.DoActionCrossThreads(() =>
            {
                MessageBox.Show(msg);
                this.Initialize();
            });
        }

        public GameStatus Status
        {
            get
            {
                return this._status;
            }
            set
            {
                this._status = value;
                switch (value)
                {
                    case GameStatus.Gaming:
                        btnReady.Visible = false;
                        btnUnready.Visible = false;
                        break;
                    case GameStatus.Ready:
                        btnReady.Visible = false;
                        btnUnready.Visible = true;
                        break;
                    case GameStatus.Unready:
                        btnUnready.Visible = false;
                        btnReady.Visible = true;
                        break;
                }
            }
        }

        #endregion
    }
}
